<div class="tmd-doc">
<p></p>
<h1 class="tmd-header-1">
How to iterate byte elements in a string?
</h1>
<p></p>
<div class="tmd-usual">
In Go, strings are assumed as UTF-8 encoded. <code class="tmd-code-span">for-range</code> over a string will get the runes (Unicode code points) in the string. Then how to get the byte elements in a string? There are two ways to achieve this. The performance of these two ways is substantially equivalent.
</div>
<p></p>
<h2 class="tmd-header-2">
Way 1: use <code class="tmd-code-span">for;;</code> loop
</h2>
<p></p>
<pre class="tmd-code">
<code class="language-Go">	for i := 0; i &lt; len(aString); i++ {
		byteElement := aString[i]
		... // use byteElement
	}
</code></pre>
<p></p>
<h2 class="tmd-header-2">
Way 2: use <code class="tmd-code-span">for-range</code> loop
</h2>
<p></p>
<div class="tmd-usual">
The official Go compiler makes special optimizations so that memory allocation and bytes duplication don't happen in a conversion <code class="tmd-code-span">[]byte(aString)</code> if the result byte slice (of the conversion) is proven not to be used concurrently. For example, the conversion following the <code class="tmd-code-span">range</code> keyword doesn't allocate and duplicate the underlying bytes.
</div>
<p></p>
<pre class="tmd-code">
<code class="language-Go">	for _, byteElement := range []byte(aString) {
		... // use byteElement
	}
</code></pre>
<p></p>
</div>
